package com.lw.leetcode.other.b;

/**
 * Created with IntelliJ IDEA.
 * arr
 * 1864. 构成交替字符串需要的最小交换次数
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/16 13:22
 */
public class MinSwaps {

    public static void main(String[] args) {
        MinSwaps test = new MinSwaps();

        // 1
//        String str = "111000";

        // 0
//        String str = "010";

        // -1
//        String str = "1110";

        // 1
//        String str = "100";

        // 60
        String str = "1110000000100001010100101010000101010101001000001110101000010111101100000111110001000111010111101100001100001001100101011110100011111100000000100011111011110111111011110111010100111101011111111101101100101010110000011110110100101111000100000001100000";

        int i = test.minSwaps(str);

        System.out.println(i);
    }

    public int minSwaps(String s) {
        int a = 0;
        int b = 0;
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if (c == '1') {
                a++;
            } else {
                b++;
            }
        }
        if (a == b) {
            return Math.min(find(chars, '0'), find(chars, '1'));
        }
        if (a == b + 1) {
            return find(chars, '1');
        }
        if (b == a + 1) {
            return find(chars, '0');
        }
        return -1;
    }

    private int find(char[] chars, char e) {
        int count = 0;
        for (char c : chars) {
            if (c != e) {
                count++;
            }
            e ^= 1;
        }
        return count >> 1;
    }

}
